home *** CD-ROM | disk | FTP | other *** search
/ The 640 MEG Shareware Studio 2 / The 640 Meg Shareware Studio CD-ROM Volume II (Data Express)(1993).ISO / clang / ctutor.zip / CHAP12.TXT < prev    next >
Text File  |  1987-07-04  |  27KB  |  588 lines

  1.                       Chapter 12 - Dynamic Allocation
  2.  
  3.  
  4.                         WHAT IS DYNAMIC ALLOCATION?
  5.  
  6.              Dynamic allocation is very intimidating to a person the
  7.         first time he comes across it, but that need not be.  Simply
  8.         relax  and  read this chapter carefully and you will have  a
  9.         good grounding in a very valuable programming resource.  All
  10.         of the variables in every program up to this point have been
  11.         static  variables as far as we  are  concerned.   (Actually,
  12.         some  of  them  have been "automatic" and  were  dynamically
  13.         allocated for you by the system,  but it was transparent  to
  14.         you.)   In  this  chapter,  we will study  some  dynamically
  15.         allocated variables.   They are simply variables that do not
  16.         exist   when  the  program  is  loaded,   but  are   created
  17.         dynamically as they are needed.  It is possible, using these
  18.         techniques, to create as many variables as needed, use them,
  19.         and deallocate their space for use by other  variables.   As
  20.         usual,  the best teacher is an example,  so load and display
  21.         the program named DYNLIST.C.
  22.  
  23.              We  begin by defining a named structure "animal" with a
  24.         few  fields  pertaining  to dogs.   We  do  not  define  any
  25.         variables of this type,  only three pointers.  If you search
  26.         through  the  remainder  of the program,  you will  find  no
  27.         variables defined so we have nothing to store data in.   All
  28.         we have to work with are three pointers, each of which point
  29.         to the defined structure.   In order to do anything, we need
  30.         some variables, so we will create some dynamically.
  31.  
  32.                          DYNAMIC VARIABLE CREATION
  33.  
  34.              The first program statement, which assigns something to
  35.         the   pointer  "pet1"  will  create  a   dynamic   structure
  36.         containing  three variables.   The heart of the statement is
  37.         the "malloc" function buried in the middle of the statement.
  38.         This  is a "memory allocate" function that needs  the  other
  39.         things to completely define it.   The "malloc" function,  by
  40.         default, will allocate a piece of memory on a "heap" that is
  41.         "n" characters in length and will be of type character.  The
  42.         "n"  must be specified as the only argument to the function.
  43.         We will discuss "n" shortly,  but first we need to define  a
  44.         "heap".
  45.  
  46.                               WHAT IS A HEAP?
  47.  
  48.              Every compiler has a set of limitations on it as to how
  49.         big  the executable file can be,  how many variables can  be
  50.         used,  how long the source file can be, etc.  One limitation
  51.         placed  on users by the Turbo C compiler is a limit  of  64K
  52.         for  the  executable code if you happen to be in  the  small
  53.         memory   model.    This  is  because  the  IBM-PC   uses   a
  54.         microprocessor  with  a 64K segment size,  and  it  requires
  55.  
  56.  
  57.                                   Page 85
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.                       Chapter 12 - Dynamic Allocation
  68.  
  69.  
  70.         special  calls to use data outside of a single segment.   In
  71.         order  to keep the program small and efficient, these  calls
  72.         are  not  used, and the memory space is  limited  but  still
  73.         adequate for most programs.
  74.  
  75.              In  this  model Turbo C defines two  heaps,  the  first
  76.         being called a "heap", and the second being called the  "far
  77.         heap".   The "heap" is an area within the 64K boundary  that
  78.         can  store dynamically allocated date and the "far heap"  is
  79.         an  area outside of this 64K boundary which can be  accessed
  80.         by the program to store data and variables.
  81.  
  82.              The  data  and variables are put on the "heap"  by  the
  83.         system  as  calls to "malloc" are made.   The  system  keeps
  84.         track  of where the data is stored.  Data and variables  can
  85.         be deallocated as desired leading to holes in the heap.  The
  86.         system  knows  where  the holes are and will  use  them  for
  87.         additional  data  storage as more "malloc" calls  are  made.
  88.         The  structure  of  the heap is  therefore  a  very  dynamic
  89.         entity, changing constantly.
  90.  
  91.              The  data  and variables are put on the "far  heap"  by
  92.         utilizing  calls  to  "farmalloc",  "farcalloc",  etc.   and
  93.         removed  through use of the function "farfree".  Study  your
  94.         Turbo  C  Reference Guide for details of how  to  use  these
  95.         features.
  96.  
  97.                             MORE ABOUT SEGMENTS
  98.  
  99.              Turbo  C  gives the user a choice of memory  models  to
  100.         use.  The  user  has a choice of using a model  with  a  64K
  101.         limitation  for  either program or data leading to  a  small
  102.         fast  program or selecting a 640K limitation  and  requiring
  103.         longer  address calls leading to less efficient  addressing.
  104.         Using  the  larger  address  space  requires  inter  segment
  105.         addressing,  resulting in the slightly slower running  time.
  106.         The  time  is probably insignificant in most  programs,  but
  107.         there are other considerations.
  108.  
  109.              If a program uses no more than 64K bytes for the  total
  110.         of its code and memory and if it doesn't use a stack, it can
  111.         be  made  into  a  .COM file.  With Turbo  C  this  is  only
  112.         possible by using the tiny memory model.  Since a .COM  file
  113.         is  already in a memory image format, it can be loaded  very
  114.         quickly  whereas  a  file in an .EXE format  must  have  its
  115.         addresses  relocated  as  it is loaded.   Therefore  a  tiny
  116.         memory  model can generate a program that loads faster  than
  117.         one  generated with a larger memory model.  Don't  let  this
  118.         worry  you,  it is a fine point that few  programmers  worry
  119.         about.
  120.  
  121.  
  122.  
  123.                                   Page 86
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.                       Chapter 12 - Dynamic Allocation
  134.  
  135.  
  136.              Even  more  important than the need to stay within  the
  137.         small memory model is the need to stay within the  computer.
  138.         If  you  had a program that used several large data  storage
  139.         areas,  but not at the same time,  you could load one  block
  140.         storing  it  dynamically,  then get rid of it and reuse  the
  141.         space for the next large block of data.  Dynamically storing
  142.         each block of data in succession, and using the same storage
  143.         for  each block may allow you to run your entire program  in
  144.         the computer without breaking it up into smaller programs.
  145.  
  146.                        BACK TO THE "MALLOC" FUNCTION
  147.  
  148.              Hopefully  the above description of the "heap" and  the
  149.         overall plan for dynamic allocation helped you to understand
  150.         what  we are doing with the "malloc"  function.   It  simply
  151.         asks the system for a block of memory of the size specified,
  152.         and  gets  the block with the pointer pointing to the  first
  153.         element of the block.   The only argument in the parentheses
  154.         is the size of the block desired and in our present case, we
  155.         desire  a  block  that will hold one of  the  structures  we
  156.         defined at the beginning of the program.  The "sizeof" is  a
  157.         new  function, new to us at least, that returns the size  in
  158.         bytes of the argument within its parentheses.  It therefore,
  159.         returns the size of the structure named "animal", in  bytes,
  160.         and  that  number is sent to the system  with  the  "malloc"
  161.         call.   At the completion of that call, we have a  block  on
  162.         the heap allocated to us, with "pet1" pointing to the  block
  163.         of data.
  164.  
  165.                               WHAT IS A CAST?
  166.  
  167.  
  168.              We  still  have  a  funny  looking  construct  at   the
  169.         beginning  of the "malloc" function call.   That is called a
  170.         "cast".   The  "malloc"  function returns a block  with  the
  171.         pointer  pointing  to it being a pointer of type  "char"  by
  172.         default.  Many times, if not most, you do not want a pointer
  173.         to a "char" type variable,  but to some other type.  You can
  174.         define  the  pointer type with the construct  given  on  the
  175.         example line.   In this case we want the pointer to point to
  176.         a  structure of type "animal",  so we tell the compiler with
  177.         this strange looking construct.   Even if you omit the cast,
  178.         most compilers will return a pointer correctly,  give you  a
  179.         warning,  and  go  on to produce a working program.   It  is
  180.         better programming practice to provide the compiler with the
  181.         cast to prevent getting the warning message.
  182.  
  183.                 USING THE DYNAMICALLY ALLOCATED MEMORY BLOCK
  184.  
  185.              If you remember our studies of structures and pointers,
  186.         you  will recall that if we have a structure with a  pointer
  187.         pointing  to it,  we can access any of the variables  within
  188.  
  189.  
  190.                                   Page 87
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.                       Chapter 12 - Dynamic Allocation
  201.  
  202.  
  203.         the structure.   In the next three lines of the program,  we
  204.         assign  some silly data to the structure  for  illustration.
  205.         It  should come as no surprise to you that these  assignment
  206.         statements  look just like assignments to statically defined
  207.         variables.
  208.  
  209.  
  210.              In the next statement, we assign the value of "pet1" to
  211.         "pet2" also.   This creates no new data,  we simply have two
  212.         pointers  to the same object.   Since "pet2" is pointing  to
  213.         the structure we created above,  "pet1" can be reused to get
  214.         another  dynamically allocated structure which is just  what
  215.         we  do next.   Keep in mind that "pet2" could have  just  as
  216.         easily been used for the new allocation.   The new structure
  217.         is filled with silly data for illustration.
  218.  
  219.              Finally,  we  allocate another block on the heap  using
  220.         the  pointer  "pet3",  and fill its block with  illustrative
  221.         data.
  222.  
  223.              Printing  the  data out should pose no problem  to  you
  224.         since  there is nothing new in the three  print  statements.
  225.         It is left for you to study.
  226.  
  227.                GETTING RID OF THE DYNAMICALLY ALLOCATED DATA
  228.  
  229.              Another new function is used to get rid of the data and
  230.         free  up  the  space on the heap  for  reuse,  the  function
  231.         "free".   To use it,  you simply call it with the pointer to
  232.         the   block  as  the  only  argument,   and  the  block   is
  233.         deallocated.
  234.  
  235.              In  order  to illustrate another aspect of the  dynamic
  236.         allocation and deallocation of data,  an additional step  is
  237.         included in the program on your monitor.  The pointer "pet1"
  238.         is assigned the value of "pet3".   In doing this,  the block
  239.         that  "pet1" was pointing to is effectively lost since there
  240.         is  no pointer that is now pointing to that block.   It  can
  241.         therefore never again be referred to,  changed,  or disposed
  242.         of.   That memory,  which is a block on the heap,  is wasted
  243.         from  this point on.   This is not something that you  would
  244.         ever  purposely do in a program.   It is only done here  for
  245.         illustration.
  246.  
  247.              The  first  "free" function call removes the  block  of
  248.         data that "pet1" and "pet3" were pointing to, and the second
  249.         "free"  call  removes  the block of  data  that  "pet2"  was
  250.         pointing  to.   We therefore have lost access to all of  our
  251.         data  generated earlier.   There is still one block of  data
  252.  
  253.         that  is on the heap but there is no pointer to it since  we
  254.         lost  the address to it.   Trying to "free" the data pointed
  255.  
  256.  
  257.                                   Page 88
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.  
  266.  
  267.                       Chapter 12 - Dynamic Allocation
  268.  
  269.  
  270.         to by "pet1" would result in an error because it has already
  271.         been  "freed"  by the use of "pet3".  There is  no  need  to
  272.         worry,  when  we  return to DOS, the  entire  heap  will  be
  273.         disposed  of with no regard to what we have put on it.   The
  274.         point  does  need to made that, if you lose a pointer  to  a
  275.         block  of  the heap, it forever removes that block  of  data
  276.         storage from our use and we may need that storage later.
  277.  
  278.              Compile and run the program to see if it does what  you
  279.         think it should do based on this discussion.
  280.  
  281.                         THAT WAS A LOT OF DISCUSSION
  282.  
  283.              It took nearly four pages to get through the discussion
  284.         of  the last program but it was time well spent.   It should
  285.         be  somewhat exciting to you to know that there  is  nothing
  286.         else to learn about dynamic allocation,  the last four pages
  287.         covered  it all.   Of course,  there is a lot to learn about
  288.         the  technique  of using dynamic allocation,  and  for  that
  289.         reason,  there  are two more files to study.   But the  fact
  290.         remains,  there  is  nothing  more to  learn  about  dynamic
  291.         allocation than what was given so far in this chapter.
  292.  
  293.                             AN ARRAY OF POINTERS
  294.  
  295.              Load and display the file BIGDYNL.C for another example
  296.         of dynamic allocation.   This program is very similar to the
  297.         last one since we use the same structure,  but this time  we
  298.         define an array of pointers to illustrate the means by which
  299.         you  could build a large database using an array of pointers
  300.         rather  than a single pointer to each element.   To keep  it
  301.         simple  we  define  12 elements in  the  array  and  another
  302.         working pointer named "point".
  303.  
  304.              The "*pet[12]" is new to you so a few words would be in
  305.         order.  What we have defined is an array of 12 pointers, the
  306.         first  being "pet[0]",  and the last  "pet[11]".   Actually,
  307.         since an array is itself a pointer, the name "pet" by itself
  308.         is a pointer to a pointer.   This is valid in C, and in fact
  309.         you  can  go  farther  if needed but you  will  get  quickly
  310.         confused.   I  know  of no limit as to how  many  levels  of
  311.         pointing are possible,  so a definition such as "int ****pt"
  312.         is legal as a pointer to a pointer to a pointer to a pointer
  313.         to an integer type variable, if I counted right.  Such usage
  314.         is discouraged until you gain considerable experience.
  315.  
  316.              Now that we have 12 pointers which can be used like any
  317.         other  pointer,  it  is a simple matter to write a  loop  to
  318.         allocate  a data block dynamically for each and to fill  the
  319.         respective  fields with any data desirable.   In this  case,
  320.         the  fields  are  filled with simple data  for  illustrative
  321.  
  322.  
  323.                                   Page 89
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.  
  332.  
  333.                       Chapter 12 - Dynamic Allocation
  334.  
  335.  
  336.         purposes,  but we could be reading in a  database,  readings
  337.         from some test equipment, or any other source of data.
  338.  
  339.              A  few fields are randomly picked to receive other data
  340.         to illustrate that simple assignments can be used,  and  the
  341.         data is printed out to the monitor.   The pointer "point" is
  342.         used  in the printout loop only to serve as an illustration,
  343.         the  data could have been easily printed using the  "pet[n]"
  344.         means  of definition.   Finally,  all 12 blocks of data  are
  345.         freed before terminating the program.
  346.  
  347.              Compile  and run this program to aid  in  understanding
  348.         this  technique.   As stated earlier,  there was nothing new
  349.         here  about  dynamic  allocation,  only about  an  array  of
  350.         pointers.
  351.  
  352.                                A LINKED LIST
  353.  
  354.              We  finally  come to the grandaddy of  all  programming
  355.         techniques as far as being intimidating.   Load the  program
  356.         DYNLINK.C  for an example of a dynamically allocated  linked
  357.         list.   It  sounds terrible,  but after a little time  spent
  358.         with it,  you will see that it is simply another programming
  359.         technique  made  up  of  simple components  that  can  be  a
  360.         powerful tool.
  361.  
  362.              In order to set your mind at ease,  consider the linked
  363.         list  you used when you were a child.   Your sister gave you
  364.         your birthday present,  and when you opened it,  you found a
  365.         note that said,  "Look in the hall closet."  You went to the
  366.         hall closet,  and found another note that said, "Look behind
  367.         the  TV  set."  Behind the TV you found  another  note  that
  368.         said,  "Look  under  the  coffee pot."  You  continued  this
  369.         search,  and finally you found your pair of socks under  the
  370.         dogs  feeding dish.   What you actually did was to execute a
  371.         linked  list,  the starting point being the wrapped  present
  372.         and the ending point being under the dogs feeding dish.  The
  373.         list ended at the dogs feeding dish since there were no more
  374.         notes.
  375.  
  376.              In  the program DYNLINK.C,  we will be doing  the  same
  377.         thing as your sister forced you to do.   We will however, do
  378.         it  much  faster and we will leave a little pile of data  at
  379.         each of the intermediate points along the way.  We will also
  380.         have   the  capability  to  return  to  the  beginning   and
  381.         retraverse the entire list again and again if we so desire.
  382.  
  383.                             THE DATA DEFINITIONS
  384.  
  385.              This program starts similarly to the last two with  the
  386.         addition  of the definition of a constant to be used  later.
  387.  
  388.  
  389.                                   Page 90
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.                       Chapter 12 - Dynamic Allocation
  400.  
  401.  
  402.         The  structure  is nearly the same as that used in the  last
  403.         two programs except for the addition of another field within
  404.         the structure,  the pointer.   This pointer is a pointer  to
  405.         another  structure  of  this same type and will be  used  to
  406.         point to the next structure in order.  To continue the above
  407.         analogy,  this pointer will point to the next note, which in
  408.         turn will contain a pointer to the next note after that.
  409.  
  410.              We  define three pointers to this structure for use  in
  411.         the program, and one integer to be used as a counter, and we
  412.         are ready to begin using the defined structure for  whatever
  413.         purpose  we  desire.   In  this case,  we  will  once  again
  414.         generate nonsense data for illustrative purposes.
  415.  
  416.                               THE FIRST FIELD
  417.  
  418.              Using  the  "malloc" function,  we request a  block  of
  419.         storage on the "heap" and fill it with data.  The additional
  420.         field in this example, the pointer, is assigned the value of
  421.         NULL, which is only used to indicate that this is the end of
  422.         the  list.   We  will  leave  the pointer  "start"  at  this
  423.         structure,  so  that  it  will always  point  to  the  first
  424.         structure of the list.   We also assign "prior" the value of
  425.         "start" for reasons we will see soon.  Keep in mind that the
  426.         end  points of a linked list will always have to be  handled
  427.         differently  than those in the middle of a list.   We have a
  428.         single  element  of  our  list now and  it  is  filled  with
  429.         representative data.
  430.  
  431.                        FILLING ADDITIONAL STRUCTURES
  432.  
  433.              The  next group of assignments and  control  statements
  434.         are  included  within a "for" loop so we can build our  list
  435.         fast  once  it is defined.   We will go through the  loop  a
  436.         number  of times equal to the constant "RECORDS" defined  at
  437.         the  beginning  of  our  program.   Each  time  through,  we
  438.         allocate memory,  fill the first three fields with nonsense,
  439.         and  fill the pointers.   The pointer in the last record  is
  440.         given  the  address of this new record because  the  "prior"
  441.         pointer is pointing to the prior record.  Thus "prior->next"
  442.         is given the address of the new record we have just  filled.
  443.         The  pointer in the new record is assigned the value "NULL",
  444.         and  the  pointer "prior" is given the address of  this  new
  445.         record  because the next time we create a record,  this  one
  446.         will  be  the  prior  one at  that  time.   That  may  sound
  447.         confusing  but it really does make sense if you  spend  some
  448.         time studying it.
  449.  
  450.              When  we have gone through the "for" loop 6  times,  we
  451.         will  have  a  list  of 7 structures including  the  one  we
  452.  
  453.  
  454.  
  455.                                   Page 91
  456.  
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.  
  464.  
  465.                       Chapter 12 - Dynamic Allocation
  466.  
  467.  
  468.         generated  prior  to  the loop.   The  list  will  have  the
  469.         following characteristics.
  470.  
  471.  
  472.         1. "start" points to the first structure in the list.
  473.  
  474.         2. Each structure contains a pointer to the next structure.
  475.  
  476.         3. The last structure has a pointer  that points to NULL and
  477.            can be used to detect the end.
  478.  
  479.            start->struct1              This diagram should aid in
  480.                   name              understanding the structure of
  481.                   breed             the data at this point.
  482.                   age
  483.                   point->struct2
  484.                          name
  485.                          breed
  486.                          age
  487.                          point->struct3
  488.                                 name
  489.                                 breed
  490.                                 age
  491.                                 point-> . . . . struct7
  492.                                                 name
  493.                                                 breed
  494.                                                 age
  495.                                                 point->NULL
  496.  
  497.  
  498.              It should be clear to you,  if you understand the above
  499.         structure,  that  it is not possible to simply jump into the
  500.         middle of the structure and change a few values.   The  only
  501.         way  to  get  to the third structure is by starting  at  the
  502.         beginning  and working your way down through  the  structure
  503.         one  record at a time.   Although this may seem like a large
  504.         price  to  pay for the convenience of putting so  much  data
  505.         outside of the program area,  it is actually a very good way
  506.         to store some kinds of data.
  507.  
  508.             A  word processor would be a good application  for  this
  509.         type  of data structure because you would never need to have
  510.         random access to the data.   In actual practice, this is the
  511.         basic type of storage used for the text in a word  processor
  512.         with one line of text per record.   Actually, a program with
  513.         any degree of sophistication would use a doubly linked list.
  514.         This  would  be  a list with two pointers  per  record,  one
  515.         pointing down to the next record,  and the other pointing up
  516.         to the record just prior to the one in question.  Using this
  517.         kind  of a record structure would allow traversing the  data
  518.         in either direction.
  519.  
  520.  
  521.                                   Page 92
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.  
  530.  
  531.                       Chapter 12 - Dynamic Allocation
  532.  
  533.  
  534.  
  535.                            PRINTING THE DATA OUT
  536.  
  537.              To print the data out, a similar method is used as that
  538.         used to generate the data.  The pointers are initialized and
  539.         are  then  used  to go from record  to  record  reading  and
  540.         displaying   each  record  one  at  a  time.    Printing  is
  541.         terminated when the NULL on the last record is found, so the
  542.         program  doesn't even need to know how many records  are  in
  543.         the list.   Finally, the entire list is deleted to make room
  544.         in  memory  for any additional data that may be  needed,  in
  545.         this case, none.  Care must be taken to assure that the last
  546.         record is not deleted before the NULL is checked.   Once the
  547.         data is gone,  it is impossible to know if you are  finished
  548.         yet.
  549.  
  550.                MORE ABOUT DYNAMIC ALLOCATION AND LINKED LISTS
  551.  
  552.              It  is  not difficult,  and it is not trivial,  to  add
  553.         elements into the middle of a linked lists.  It is necessary
  554.         to create the new record,  fill it with data,  and point its
  555.         pointer to the record it is desired to precede.   If the new
  556.         record  is  to be installed between the  3rd  and  4th,  for
  557.         example,  it is necessary for the new record to point to the
  558.         4th record,  and the pointer in the 3rd record must point to
  559.         the new one.  Adding a new record to the beginning or end of
  560.         a  list are each special cases.   Consider what must be done
  561.         to add a new record in a doubly linked list.
  562.  
  563.              Entire books are written describing different types  of
  564.         linked lists and how to use them,  so no further detail will
  565.         be  given.   The amount of detail given should be sufficient
  566.         for a beginning understanding of C and its capabilities.
  567.  
  568.                        ANOTHER NEW FUNCTION - CALLOC
  569.  
  570.              One  more  function must  be  mentioned,  the  "calloc"
  571.         function.   This  function  allocates a block of memory  and
  572.         clears  it  to  all  zeros  which  may  be  useful  in  some
  573.         circumstances.   It is similar to "malloc" and will be  left
  574.         as an exercise for you to read about and use "calloc" if you
  575.         desire.
  576.  
  577.         PROGRAMMING EXERCISES
  578.  
  579.         1.  Rewrite the example program STRUCT1.C from chapter 11 to
  580.             dynamically allocate the two structures.
  581.  
  582.         2.  Rewrite the example program STRUCT2.C from chapter 11 to
  583.             dynamically allocate the 12 structures.
  584.  
  585.  
  586.  
  587.                                   Page 93
  588.